// index.tsx
import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { Space, Table, Tag, Switch, Button, message, Input, Popconfirm, Typography, Tooltip, Avatar, Modal } from 'antd';
import type { TableProps, SpinProps } from 'antd';
import { SearchOutlined, DeleteOutlined, EditOutlined, UserOutlined, ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons';

import type { IMembers } from '~/types/members';
import MemberFormModal from './edit';

// 类型定义
type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection'];
type PaginationConfig = { current: number; pageSize: number; };

const { Column, ColumnGroup } = Table;
const { confirm } = Modal;

// 常量定义
const PAGE_SIZE_OPTIONS = ['5', '10', '20', '50', '100'];
const DEFAULT_CURRENT_PAGE = 1;
const DEFAULT_PAGE_SIZE = 5;

// 静态数据 - 作为初始数据源
const INITIAL_MEMBERS: IMembers[] = [
  {
    id: 1,
    fileNumber: 'JK2024001',
    name: '张三',
    sex: '男',
    age: 35,
    healthMgrName: '李医生',
    phoneNumber: '13800138001',
    birthday: '1989-05-15',
    status: 'active'
  },
  {
    id: 2,
    fileNumber: 'JK2024002',
    name: '李四',
    sex: '女',
    age: 28,
    healthMgrName: '王医生',
    phoneNumber: '13800138002',
    birthday: '1996-08-22',
    status: 'active'
  },
  {
    id: 3,
    fileNumber: 'JK2024003',
    name: '王五',
    sex: '男',
    age: 42,
    healthMgrName: '赵医生',
    phoneNumber: '13800138003',
    birthday: '1982-03-10',
    status: 'inactive'
  },
  {
    id: 4,
    fileNumber: 'JK2024004',
    name: '赵六',
    sex: '女',
    age: 31,
    healthMgrName: '钱医生',
    phoneNumber: '13800138004',
    birthday: '1993-11-05',
    status: 'active'
  },
  {
    id: 5,
    fileNumber: 'JK2024005',
    name: '孙七',
    sex: '男',
    age: 39,
    healthMgrName: '孙医生',
    phoneNumber: '13800138005',
    birthday: '1985-07-18',
    status: 'active'
  },
  {
    id: 6,
    fileNumber: 'JK2024006',
    name: '周八',
    sex: '女',
    age: 26,
    healthMgrName: '李医生',
    phoneNumber: '13800138006',
    birthday: '1998-02-28',
    status: 'active'
  },
  {
    id: 7,
    fileNumber: 'JK2024007',
    name: '吴九',
    sex: '男',
    age: 45,
    healthMgrName: '王医生',
    phoneNumber: '13800138007',
    birthday: '1979-09-12',
    status: 'inactive'
  },
  {
    id: 8,
    fileNumber: 'JK2024008',
    name: '郑十',
    sex: '女',
    age: 33,
    healthMgrName: '赵医生',
    phoneNumber: '13800138008',
    birthday: '1991-12-30',
    status: 'active'
  }
];

const Member: React.FC = () => {
  // 表格选择相关状态
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedUsers, setSelectedUsers] = useState<IMembers[]>([]);

  // 数据和加载状态 - 使用一个持久化的数据源
  const [loading, setLoading] = useState<boolean | SpinProps>({ size: 'large' });
  const [allMembers, setAllMembers] = useState<Array<IMembers>>(INITIAL_MEMBERS); // 所有数据
  const [displayedMembers, setDisplayedMembers] = useState<Array<IMembers>>([]); // 当前显示的数据
  const [totalCount, setTotalCount] = useState<number>(0);

  // 搜索和分页状态
  const [searchName, setSearchName] = useState<string>('');
  const [pagination, setPagination] = useState<PaginationConfig>({
    current: DEFAULT_CURRENT_PAGE,
    pageSize: DEFAULT_PAGE_SIZE,
  });

  // 表单弹窗相关状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('添加会员');
  const [currentUserId, setCurrentUserId] = useState<number | null>(null);
  const [formInitialValues, setFormInitialValues] = useState<Partial<IMembers> | undefined>();

  // 处理选择变化
  const handleSelectChange = useCallback((
    newSelectedRowKeys: React.Key[],
    selectedRows: IMembers[]
  ) => {
    setSelectedRowKeys(newSelectedRowKeys);
    setSelectedUsers(selectedRows);
  }, []);

  // 行选择配置
  const rowSelection: TableRowSelection<IMembers> = useMemo(() => ({
    selectedRowKeys,
    onChange: handleSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: '选择奇数行',
        onSelect: (changeableRowKeys) => {
          const newSelectedRowKeys = changeableRowKeys.filter((_, index) => index % 2 === 0);
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: 'even',
        text: '选择偶数行',
        onSelect: (changeableRowKeys) => {
          const newSelectedRowKeys = changeableRowKeys.filter((_, index) => index % 2 !== 0);
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  }), [selectedRowKeys, handleSelectChange]);

  // 获取会员数据 - 基于持久化的 allMembers 数据
  const fetchUsers = useCallback((
    page: number = pagination.current,
    pageSize: number = pagination.pageSize,
    name: string = searchName // 使用当前搜索条件
  ) => {
    setLoading({ size: 'large' });

    // 模拟网络延迟
    setTimeout(() => {
      try {
        let filteredMembers = [...allMembers];

        // 根据搜索名称过滤
        if (name && name.trim()) {
          filteredMembers = filteredMembers.filter(member =>
            member.name && member.name.includes(name.trim())
          );
        }

        // 计算分页
        const startIndex = (page - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        const paginatedMembers = filteredMembers.slice(startIndex, endIndex);

        setDisplayedMembers(paginatedMembers);
        setTotalCount(filteredMembers.length);
        // 只有在初始加载时显示成功消息，搜索时不显示
        if (!name) {
          message.success('数据加载成功');
        }
      } catch (error) {
        console.error('获取会员数据失败:', error);
        message.error('获取会员数据失败，请稍后重试');
      } finally {
        setLoading(false);
      }
    }, 300);
  }, [allMembers]); // 移除 pagination 和 searchName 依赖

  // 初始化数据
  useEffect(() => {
    fetchUsers();
  }, []); // 空依赖，只在组件挂载时执行

  // 处理搜索
  const handleSearch = useCallback(() => {
    // 重置到第一页并搜索
    const newPagination = { ...pagination, current: DEFAULT_CURRENT_PAGE };
    setPagination(newPagination);
    fetchUsers(DEFAULT_CURRENT_PAGE, pagination.pageSize, searchName);
  }, [fetchUsers, pagination.pageSize, searchName]);

  // 处理分页变化
  const handlePaginationChange = useCallback((page: number, pageSize: number) => {
    const newPagination = { current: page, pageSize };
    setPagination(newPagination);
    fetchUsers(page, pageSize, searchName);
  }, [fetchUsers, searchName]);

  // 删除单个会员 - 更新持久化数据
  const handleDeleteUser = useCallback((id: number, userName: string) => {
    try {
      setLoading(true);

      // 模拟网络延迟
      setTimeout(() => {
        // 更新持久化数据
        const updatedMembers = allMembers.filter(member => member.id !== id);
        setAllMembers(updatedMembers);

        // 重新获取当前页数据
        fetchUsers(pagination.current, pagination.pageSize, searchName);

        message.success(`会员 "${userName}" 删除成功！`);
      }, 300);
    } catch (error) {
      console.error('删除会员失败:', error);
      message.error('删除会员失败，请稍后重试');
      setLoading(false);
    }
  }, [allMembers, pagination, searchName, fetchUsers]);

  // 批量删除会员 - 更新持久化数据
  const handleBatchDelete = useCallback(() => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要删除的会员');
      return;
    }

    confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      content: `确定要删除选中的 ${selectedRowKeys.length} 个会员吗？此操作不可撤销。`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          setLoading(true);

          // 模拟网络延迟
          setTimeout(() => {
            // 更新持久化数据
            const updatedMembers = allMembers.filter(member => !selectedRowKeys.includes(member.id));
            setAllMembers(updatedMembers);

            // 重新获取当前页数据
            fetchUsers(pagination.current, pagination.pageSize, searchName);

            // 获取选中会员的姓名列表
            const memberName = selectedUsers.map(user => user.name).join('、');
            message.success(`成功删除 ${memberName} 等 ${selectedRowKeys.length} 个会员！`);

            // 清空选择
            setSelectedRowKeys([]);
            setSelectedUsers([]);
          }, 300);
        } catch (error) {
          console.error('批量删除会员失败:', error);
          message.error('批量删除会员失败，请稍后重试');
          setLoading(false);
        }
      },
    });
  }, [selectedRowKeys, selectedUsers, allMembers, pagination, searchName, fetchUsers]);

  // 显示添加会员弹窗
  const showAddModal = () => {
    setModalTitle('添加会员');
    setCurrentUserId(null);
    setFormInitialValues(undefined);
    setIsModalVisible(true);
  };

  // 显示编辑会员弹窗
  const showEditModal = (record: IMembers) => {
    setModalTitle('修改会员');
    setCurrentUserId(record.id);
    setFormInitialValues(record);
    setIsModalVisible(true);
  };

  // 表单操作成功后的回调 - 更新持久化数据
  const handleFormSuccess = (newMemberData: any) => {
    if (currentUserId) {
      // 编辑模式 - 更新现有会员
      const updatedMembers = allMembers.map(member =>
        member.id === currentUserId
          ? { ...member, ...newMemberData }
          : member
      );
      setAllMembers(updatedMembers);

      // 重新获取当前页数据
      fetchUsers(pagination.current, pagination.pageSize, searchName);

      message.success('会员修改成功！');
    } else {
      // 添加模式 - 添加新会员
      const newId = allMembers.length > 0 ? Math.max(...allMembers.map(m => m.id)) + 1 : 1;
      const newMember = {
        ...newMemberData,
        id: newId,
        fileNumber: newMemberData.fileNumber || `JK${new Date().getFullYear()}${String(newId).padStart(3, '0')}`,
        age: newMemberData.age || 25,
        status: 'active'
      };

      const updatedMembers = [...allMembers, newMember];
      setAllMembers(updatedMembers);

      // 重新获取当前页数据
      fetchUsers(pagination.current, pagination.pageSize, searchName);

      message.success('会员添加成功！');
    }
  };

  // 修改会员状态 - 更新持久化数据
  const changeUserStatus = useCallback((checked: boolean, record: IMembers) => {
    confirm({
      title: '确认修改',
      icon: <ExclamationCircleOutlined />,
      content: `确定要${checked ? '激活' : '冻结'}此会员吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          setLoading(true);

          // 模拟网络延迟
          setTimeout(() => {
            // 更新持久化数据
            const updatedMembers = allMembers.map(member =>
              member.id === record.id
                ? { ...member, status: checked ? 'active' : 'inactive' }
                : member
            );
            setAllMembers(updatedMembers);

            // 重新获取当前页数据
            fetchUsers(pagination.current, pagination.pageSize, searchName);

            message.success(`会员已成功${checked ? '激活' : '冻结'}！`);
          }, 300);
        } catch (error) {
          console.error('修改会员状态失败:', error);
          message.error('修改会员状态失败，请稍后重试');
          setLoading(false);
        }
      },
    });
  }, [allMembers, pagination, searchName, fetchUsers]);

  // 处理输入框按回车搜索
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSearch();
    }
  };

  // 处理清除搜索
  const handleClearSearch = () => {
    setSearchName('');
    // 清除搜索后重新获取所有数据
    fetchUsers(DEFAULT_CURRENT_PAGE, pagination.pageSize, '');
  };

  return (
    <div className="users-container" style={{ padding: '20px' }}>
      <div style={{
        marginBottom: 16,
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
      }}>
        <Space size="middle">
          <Input
            placeholder="请输入会员名搜索"
            value={searchName}
            onChange={(e) => setSearchName(e.target.value)}
            onPressEnter={handleKeyPress}
            onBlur={() => {
              // 输入框失去焦点时，如果有搜索内容但未搜索，自动搜索
              if (searchName.trim()) {
                handleSearch();
              }
            }}
            style={{ width: 300 }}
            allowClear
            onClear={handleClearSearch}
          />
          <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
            搜索
          </Button>
          <Button
            type="primary"
            style={{ marginLeft: 8 }}
            icon={<PlusOutlined />}
            onClick={showAddModal}
          >
            添加会员
          </Button>
        </Space>

        <Button
          danger
          icon={<DeleteOutlined />}
          disabled={selectedRowKeys.length === 0}
          onClick={handleBatchDelete}
        >
          批量删除
        </Button>
      </div>

      <Table<IMembers>
        loading={loading}
        dataSource={displayedMembers}
        rowKey="id"
        rowSelection={rowSelection}
        pagination={{
          total: totalCount,
          current: pagination.current,
          pageSize: pagination.pageSize,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 条`,
          showSizeChanger: true,
          showQuickJumper: true,
          pageSizeOptions: PAGE_SIZE_OPTIONS,
          position: ['bottomCenter'],
          onChange: handlePaginationChange
        }}
        scroll={{ x: 'max-content' }}
      >
        <Column title="编号" dataIndex="id" key="id" width={80} />
        <Column title="档案号" dataIndex="fileNumber" key="fileNumber" width={80} />
        <Column title="姓名" dataIndex="name" key="name" width={120} />

        <Column title="性别" dataIndex="sex" key="sex" width={80} render={(sex) => (
          <Tag color={sex === '男' ? 'blue' : 'pink'}>
            {sex}
          </Tag>
        )}
        />

        <Column title="年龄" dataIndex="age" key="age" width={80} />
        {/* <Column title="健康管理师" dataIndex="healthMgrName" key="healthMgrName" width={150} /> */}
        <Column title="手机号码" dataIndex="phoneNumber" key="phoneNumber" width={140} ellipsis={{ showTitle: false }} render={(phone) => (
          <Tooltip title={phone} placement="top">
            {phone}
          </Tooltip>
        )}
        />
        <Column title="注册时间" dataIndex="birthday" key="birthday" width={120} render={(birthday) => (
          <Tooltip title={birthday} placement="top">
            {birthday?.substr(0, 10)}
          </Tooltip>
        )} />

        <Column title="状态" dataIndex="status" key="status" width={100} render={(status, record: IMembers) => (
          <Switch
            checked={status === 'active'}
            onChange={(checked) => changeUserStatus(checked, record)}
            checkedChildren="激活"
            unCheckedChildren="冻结"
          />
        )} />

        <Column title="操作" key="action" width={180} render={(_: any, record: IMembers) => (
          <Space size="middle">
            <Button
              type="primary"
              size="small"
              icon={<EditOutlined />}
              onClick={() => showEditModal(record)}
            >
              修改
            </Button>
            <Popconfirm
              title={`确定要删除会员 "${record.name}" 吗？`}
              onConfirm={() => handleDeleteUser(record.id, record.name)}
              okText="确定"
              cancelText="取消"
            >
              <Button danger icon={<DeleteOutlined />} size="small">
                删除
              </Button>
            </Popconfirm>
          </Space>
        )}
        />
      </Table>

      {/* 引入独立的会员表单弹窗组件 */}
      <MemberFormModal
        visible={isModalVisible}
        title={modalTitle}
        initialValues={formInitialValues}
        id={currentUserId}
        loading={!!loading}
        onCancel={() => setIsModalVisible(false)}
        onSuccess={handleFormSuccess}
      />
    </div>
  );
};

export default Member;